<template>
  <div>
    <div class="play-root">
      <!-- <iframe class="iframe" :src="url"></iframe> -->
      <!-- <video id="video1" controls=false :src="url" class="video"></video> -->
      <!-- <video-player class="video-player vjs-custom-skin" 
            ref="videoPlayer" 
            playsinline
            :options="playerOptions"
            @ended="onPlayerEnded($event)" webkit-playsinline="true" >
        </video-player> -->
      <!-- <video
    ref="videoPlayerRef"
    class="video-js"
  >
    <source
      :src="url"
      type="video/mp4"
    >
  </video> -->
      <!-- <vue-core-video-player  src="http://qtyj.safetyhua.com//Uploads/00031/20230516/c84abf3c-df52-4f75-82c3-b590a276a817.mp4" title= "测试"  :controls="false"  :loop="false"/> -->
      <!-- <video-player class="video-player vjs-custom-skin"
   ref="videoPlayer"
   :playsinline="true"
   :options="playerOptions"
   @timeupdate="handleTimeUpdate($event)">
  </video-player>
  <div @click="handleClickProgress"></div> -->
      <!-- <d-player ref="player" id="player" :options="options"></d-player> -->
      <div>
        <div id="dplayer" v-show="dpshow" class="dplayer-hide-controller"></div>
        <!-- <button id="btn" class="copy" @click="evt">
      点击全屏
    </button> -->
      </div>
    </div>
    <div class="playerstar" v-show="playerstarshow" @click="quan">
      <img src="../../../assets/Images/player_star.png">
    </div>
    <!-- <div class="bottom_submit" style="padding-top:5px" v-show="replaybtn"> -->
    <div class="bottom_submit" style="padding-top:5px" v-show="replaybtn">
      <van-button class="button" type="primary" @click="_replay()">重播</van-button>
    </div>
    <div class="bottom_submit" style="padding-top:5px">
      <van-button class="button" :disabled="nextbtn" type="primary" @click="_nextStep()">下一步</van-button>
    </div>
  </div>
</template>

<script>
import { CountDown } from "vant";
import DPlayer from 'dplayer';
import store from "@/store/index";
export default {
  components: { CountDown },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // baseUrl:"http://sp.safetyhua.com/",
      id: "",
      sid: "",
      stype: "",
      form: {},
      url: "",
      mp4: false,
      pdf: false,
      ppt: false,
      time: 0,
      title: "",
      pageNum: 1,
      pageTotalNum: 1, // 总页数
      loadedRatio: 0,
      numPages: null, // pdf 总页数
      isVideoShow: true,
      playerstarshow: true,
      playOrPause: true,
      video: null,
      videoSource: [],
      iconPlayShow: true,
      iconPauseShow: false,
      replaybtn: false,
      nextbtn: true,
      videotime: 0,
      fileid: 0,
      watchedTime: 0, // 用户观看的时间点
      Player: true,
      codetype: 0,
      dp: '',
      dpshow: true,
      isPlaying: false ,// 是否正在播放视频

    };
  },
  created() {
    
  
    if (process.env.VUE_APP_PLANTFORM == "QTYJ") {
      store.state.title = "安全桥";
      // window.open("http://qtyj.zatsafety.com/h5/#/qtyjReport/StudyFirst?codetype=1", "_self")
    }
    var paramID = this.$route.query.id;
    if(this.$route.query.n==1){
      this.nextbtn=this.$route.query.nextbtn==true
    }
    
    this.id = paramID;
    if(process.env.VUE_APP_PLANTFORM == "SP") {
      this.codetype=this.$route.query.codetype
    }else{
    if (this.$route.query.codetype != undefined) {
      if (!isNaN(parseInt(this.$route.query.codetype))) {
        this.codetype = parseInt(this.$route.query.codetype) > 0 ? 1 : 0
      }
    }
  }

    var paramSID = this.$route.query.sid;
    this.sid = paramSID;

    var paramSType = this.$route.query.stype;
    this.stype = paramSType;
    this._LoadVedioInfo()
  },
  mounted: function () {
    var that = this
    that.dp = new DPlayer({
      container: document.getElementById("dplayer"), //播放器容器
      mutex: false, //  防止同时播放多个用户，在该用户开始播放时暂停其他用户
      theme: "#b7daff", // 风格颜色，例如播放条，音量条的颜色
      loop: false, // 是否自动循环
      lang: "zh-cn", // 语言，'en', 'zh-cn', 'zh-tw'
      screenshot: true, // 是否允许截图（按钮），点击可以自动将截图下载到本地
      hotkey: true, // 是否支持热键，调节音量，播放，暂停等
      preload: "auto", // 自动预加载
      volume: 0.7, // 初始化音量
      playbackSpeed: [1], //可选的播放速度，可自定义
      video: {
        // url: 'http://qtyj.safetyhua.com//Uploads/00031/20230516/c84abf3c-df52-4f75-82c3-b590a276a817.mp4',
        // pic: 'hikarunara.png',
        // thumbnails: 'hikarunara_thumbnails.jpg'
      },
    })

    var videoTime = 0
    var logtime = 0
    that.dp.on('timeupdate', function (e) {
      var videoCurrentTime = that.dp.video.currentTime;
      if (videoCurrentTime - videoTime > 0.5) {
        that.dp.seek(videoTime);
        // dp.notice('禁止快进',2000)
      }
      videoTime = videoCurrentTime;
    })
    // that.dp.on('playing', function () {
    // 			setTimeout(function(){ 
    // 				//player-con-h5 是播放器Div的Id
    // 				document.getElementById("dplayer").classList.add("dplayer-hide-controller");
    // 			 }, 2000);
    // 		});

    that.dp.on('notice_show', function (e) {
      //   var text=e.innerText
      //   if('禁止快进'!=text&&(text.indexOf("快进")>-1||text.indexOf("快退")>-1)){
      //   }`

      e.hidden = true
    })
    that.dp.on('pause', function () {
      that.dp.fullScreen.cancel('web');
      that.playerstarshow = true
    }),
      that.dp.on('ended', function (e) {
        console.log('123')
        that.dp.fullScreen.cancel('web');
        that.nextbtn = false
        that.replaybtn = true
        that.videotime = that.dp.video.duration
      })
    // this.videofun();
    // this.getDetail();
    // 以下为隐藏一些作者的信息和视频播放源 如不需要可删除
    // document.querySelector(".dplayer-menu").remove(); //隐藏右键菜单
    // document.querySelector(".dplayer-mask").remove();
    // document.querySelector(".dplayer-info-panel-item-url").remove(); //隐藏播放源
    let length = document.querySelectorAll(".dplayer-menu-item").length;
    // document.querySelectorAll(".dplayer-menu-item")[length - 2].remove(); // 去掉作者信息
    // document.querySelectorAll(".dplayer-menu-item")[length - 1].remove(); // 去掉作者信息
    // 禁止右键下载视频
    document.oncontextmenu = new Function("event.returnValue=false;");
    document.onselectstart = new Function("event.returnValue=false;");
    // 修改循环播放显示
    document.getElementsByClassName('dplayer-setting-item dplayer-setting-loop')[0].getElementsByClassName('dplayer-label')[0].innerText = "循环播放"
    // 修改倍速播放显示
    document.getElementsByClassName('dplayer-setting-item dplayer-setting-speed')[0].getElementsByClassName('dplayer-label')[0].innerText = "播放倍速"
  },
  methods: {

    evt() {
      var that = this;
      //   that.dpshow = false;
      that.dp.play();
      // ios 下播放器全屏还是会被自带播放器接管
      // that.dp.fullScreen.request('browser');
      //所以要使用网页全屏
      that.dp.fullScreen.request('web');



      // 显示通知
      // that.dp.notice("text:测试", "time:10")
      console.log("开始播放");

    },
    quan() {
      var browser_quan = document.querySelector('.dplayer-full-icon')
      browser_quan.style.display = 'none'
      var that = this
      console.log("播放后事件监控");
      if (that.isPlaying == true) {
        that.dp.pause();
        that.dp.fullScreen.cancel('web');
        that.isPlaying = false
        that.playerstarshow = true
      } else {
        that.dp.play();
        that.playerstarshow = false
        var u = navigator.userAgent;
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        console.log('设备标志:', isiOS == true ? "苹果" : "安卓")
        if (isiOS != true) {
          that.dp.fullScreen.request('web');
        } else {
          var y = document.querySelector('video')
          //  var s= document.querySelector('.dplayer-full-in-icon')
          //  s.click()
          //IOS模式下全屏，需要额外为video添加属性playsinline
          y.webkitEnterFullscreen()
          console.log(y)
          console.log(s)
        }

        //     console.log('111',y)
        //     console.log('112',y.style.width)
        //     console.log('113',y.style.height)
        //     console.log('114',y.width)
        //     console.log('115',y.height)
        //     console.log('114',y.videoHeight)
        //     console.log('115',y.videoWidth)
        //     console.log('116',window.innerWidth)
        //     console.log('117',window.innerHeight)
        //     if(isiOS){ //判断是否为ios终端
        //       window.onresize = function () {
        //         y.webkitEnterFullscreen()
        //          y.videoHeight = window.innerHeight
        //          y.videoWidth = window.innerWidth
        // 	        }
        //     }
        that.isPlaying = true
      }

      var current = that.dp.video.currentTime;
      //只要开始播放点击视频就关闭
      //   if (current > 0) {
      //     console.log(current);
      //     // that.dpshow = false;
      //     // that.showVideo = false
      //     //设置视频时间跳转到结尾可自动触发 暂停和播放完毕
      //     // 如果 设置 跳转时间大于视频时间会小卡
      //     //设置跳转到末尾兼容性不太好
      //     // that.dp.seek(999);
      //     // that.dp.pause();
      //     // that.dp.fullScreen.cancel('browser');
      //     // ios 下取消网页全屏会导致 闪屏 可以不取消 直接隐藏元素即可
      //     //that.dp.fullScreen.cancel('web');
      //     console.log("点击取消全屏");
      //   }
      document.getElementById("dplayer").classList.add("dplayer-hide-controller");
    },


    qie() {
      var that = this
      if (that.Player) {
        //切换视频
        that.dp.switchVideo({
          url: 'http://cdn.toxicjohann.com/lostStar.mp4',
          // 设置视频第一帧为封面
          // pic:"http://cdn.toxicjohann.com/lostStar.mp4 + '?vframe/jpg/offset/1'",
          // thumbnails: 'second.jpg'
        });
        that.Player = !that.Player
        console.log("切视频1");
      } else {
        //切换视频
        that.dp.switchVideo({
          url: 'https://chimee.org/vod/1.mp4',
        });
        that.Player = !that.Player
        console.log("切视频2");
      }

    },
    onPlay() {
      this.dp.play()
    },

    handleTimeUpdate($event) {
      var a = $event
      console.log('1', a.cache_.currentTime)
      const video = this.$refs.videoPlayer;
      //   console.log('video1',video)
      if (this.isPlaying && video.currentTime > this.watchedTime) {
        // 视频播放位置超过了用户观看位置，暂停视频播放
        video.pause();
        this.isPlaying = false;
        // 弹出提示框，询问用户是否继续观看
        const isContinue = confirm("是否继续观看？");
        if (isContinue) {
          // 用户选择继续观看，将视频播放位置设置为用户观看位置，继续播放视频
          video.currentTime = this.watchedTime;
          video.play();
          this.isPlaying = true;
        }
      }
    },
    handleClickProgress() {
      const video = this.$refs.videoPlayer;
      if (!this.isPlaying) {
        // 视频未播放，无法跳转进度条
        return;
      }
      console.log('video2', video)
      // 获取用户点击的位置
      const progress = document.querySelector(".progress");
      const rect = progress.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const percent = x / rect.width;
      const currentTime = percent * video.duration;
      if (currentTime < this.watchedTime) {
        // 用户点击的位置在观看位置之前，无法跳转进度条
        return;
      }
      // 跳转视频进度条
      video.currentTime = currentTime;
    },
    // 视频播完回调
    onPlayerEnded($event) {
      var self = this
      self.nextbtn = false
      self.replaybtn = true
      self.videotime = $event.cache_.duration
    },

    _LoadVedioInfo() {
      var self = this;
      var _fileid = this.$route.query.fileid
      console.log('_fileid', _fileid)
      if (_fileid == undefined || _fileid == null) {
        _fileid = 0
      }
      
      // this.$axios.post('/UserStudyTime/FindVideoInfo', { fileid: parseInt(_fileid) }).then((res) => {
        var _codetype=null
        if(this.codetype==3){
            _codetype=3
        }
      this.$axios.post('/UserStudyTime/FindVideoInfo', { fileid: parseInt(_fileid),IndustryType:_codetype }).then((res) => {
        self.fileid = res.data.ID;
        self.url = self.baseUrl + res.data.FileUrl;
        console.log(self.url)
        self.dp.switchVideo({
          url: self.url,
        });
        // self.playerOptions.sources=[{type:"video/mp4",src:self.url}]
        // self.videoSource=[{src:self.url,resolution:720}]
        // console.log(res)
        // console.log(self.baseUrl)
      });
    },

    // 上一页
    _replay() {
      var browser_quan = document.querySelector('.dplayer-full-icon')
      browser_quan.style.display = 'none'
      this.dp.seek(0)
      this.playerstarshow = false
      this.dp.play()
      // let video = document.querySelectorAll('video1')
      // let  video = document.getElementById('video1')
      // console.log("pauseVideo" ) 
      // // video.play()
      // console.log("播放进度"+video.currentTime)
      // video.pause()
      // video.currentTime=0
      // video.play()
      var u = navigator.userAgent;
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      console.log('设备标志:', isiOS == true ? "苹果" : "安卓")
      if (isiOS != true) {
        this.dp.fullScreen.request('web');
      } else {
        var y = document.querySelector('video')
        //IOS模式下全屏，需要额外为video添加属性playsinline
        //  var s= document.querySelector('.dplayer-full-in-icon')
        //  s.click()
        y.webkitEnterFullscreen()
        console.log(y)
      }


      this.isPlaying = true
      this.nextbtn = true
      this.replaybtn = false
      // if (this.playOrPause) {
      //     video.pause()
      //     this.iconPlayShow = true
      //     this.iconPauseShow = false
      // } else {
      //     video.play()
      //     this.iconPlayShow = false
      //     this.iconPauseShow = true
      // }
      // this.playOrPause = !this.playOrPause
      // this.displayBtn()
    },
    _nextStep() {
      if (process.env.VUE_APP_PLANTFORM == "SP") {
        this.$router.push({ path: "/qtyjReport/study3", query: { videotime: this.videotime, fileid: this.fileid, codetype: this.codetype } })
      } else {
        this.$router.push({ path: "/qtyjReport/study", query: { videotime: this.videotime, fileid: this.fileid, codetype: this.codetype } })

        // window.open("http://qtyj.zatsafety.com/h5/#/qtyjReport/study?videotime="+this.videotime+"&fileid="+this.fileid+"&codetype="+this.codetype, "_self")
      }

    },
    loadFinish() {
      if (this.title == "当前学习进度") {
        this.$refs.countDown.start();
      }
      console.log("加载完毕！");
    },
    videofun() {
      var self = this
      let _video = document.getElementById('video1')

      _video.addEventListener('ended', function () {
        // 结束播放
        console.log('时长', _video.duration)
        self.nextbtn = false
        self.replaybtn = true
        self.videotime = _video.duration
      })
    },
    // 下一页
    nextPage() {
      let page = this.pageNum;
      page = page < this.pageTotalNum ? page + 1 : 1;
      this.pageNum = page;
    },

    timeChange(timeData) {
      let newTime =
        (timeData.days * 60 + timeData.minutes * 60 + timeData.seconds) % 15;
      if (newTime == 0) {
        this.$axios
          .post("/TrainStudyRecord/Study", {
            id: this.form.ID,
            sid: this.sid,
            stype: this.stype,
            guid: this.form.CurrentGuid,
            silence: true,
          })
          .then((res) => {
            this.form.CurrentProgress = res.data.CurrentProgress;
            if (res.data.CurrentProgress == 100) {
              this.title = "当前进度";
            } else {
              this.title = "当前学习进度";
            }
          })
          .catch((err) => {
            console.log("err", err);
          });
      }
    },
    getDetail() {
      const _this = this;
      let params = { id: this.id, sid: this.sid, stype: this.stype };
      this.$axios
        .get("/TrainRes/GetStudyInfo", { params: params })
        .then((res) => {
          if (res.data.AttMiddlePath.indexOf("http") == -1) {
            //this.url = this.baseUrl + res.data.AttMiddlePath;
            _this.url =
              this.baseUrl +
              "/Plugins/pdfjs/web/viewer.html?file=" +
              res.data.AttMiddlePath;
          } else {
            _this.url =
              "/Plugins/pdfjs/web/viewer.html?file=" + res.data.AttMiddlePath;
          }
          _this.form = res.data;
          if (res.data.CurrentProgress == 100) {
            _this.title = "当前进度";
          } else {
            _this.title = "当前学习进度";
            _this.time = res.data.LeftStudyHours * 60 * 1000;
            _this.$nextTick(() => {
              _this.$refs.countDown.start()
            })
          }
        });
    },
  },
};
</script>

<style lang="less">
/* /deep/ .vjs-progress-control{
    pointer-events: none !important;
 } */
/* 进度条 */
video::-webkit-media-controls-timeline {
  display: none;
}

#dplayer {
  height: 300px;
}

/deep/ .vjs-progress-control {
  display: none;
}

/deep/.dplayer-danmaku-item {
  span {
    border: none !important; //去掉弹幕边框
  }

  .dplayer-notice {
    /* 快退进提示 */
    display: none;
  }

  .dplayer {
    width: 100%;
  }

  .dplayer-controller {
    /* 底部控制条 */
    display: none;
  }

  .dplayer-notice {
    /* 快退进提示 */
    display: none;
  }


  .dplayer-menu.dplayer-menu-show {
    /* 右键信息 */
    display: none;
  }

  .dplayer-mask {
    /* 悬浮层 */
    display: inline-block;
  }

  /* 在浏览器找到对应的class名称。然后通过穿透对样式进行更改 */

  /* 禁止循环播放显示 */
  /* .paly-root >>> .dplayer-setting-loop {
    background-color: cyan;
    display: none;
  } */

  /* 禁止出现快进多少秒提示 */
  .play-root /deep/ .dplayer-notice {
    display: none;
  }

  /* 禁止右键自定义列表 */
  /* .play-root /deep/ .dplayer-menu-show{
     display: none;
  } */

}

.playerstar {
  position: absolute;
  top: 45px;
  width: 100%;
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(112, 104, 104, 0.916);
}

.playerstar img {
  width: 50%;
}

.video-hd {
  z-index: 99;
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  font-size: 14px;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.5);
}

.video-hd>div {
  display: flex;
  align-items: center;
}

.video {
  width: 100%;
  height: calc(100vh - 200px);
}

.iframe {
  width: 100%;
  height: calc(100vh - 200px);

}

.bottom_submit {
  width: 100%;
  text-align: center;
}

.button {
  width: 98%;
}

/* // .fixed {
// 	position: fixed;
// 	top: 0;
// 	left: 0;
// 	bottom: 0;
// 	right: 0;
// 	background: #000;
// }

// .transform-rotate {
// 	position: fixed;
// 	top: 0;
// 	bottom: 0;
// 	transform-origin: 0 50%;
// 	transform: rotate(90deg) translate(-50%, -4%);
// }
//进度条
video::-webkit-media-controls-timeline {
    display: none;
} */
</style>